#coding:utf-8

import json

def initM(location):
    with open(location) as f:
        M1 = json.loads(f.read())
    M2 = dict()
    for v,k in M1.items():
        M2[str(k)] = v
    return M2


def processT(T,location1,location2):
    f1 = open(location1,mode='r')
    f2 = open(location2,mode='w')
    
    count = 0
    for line in f1:
        t = T[str(count)]
        s = line.strip()
        line = json.dumps((t,s),ensure_ascii=False)
        f2.write(line.encode('utf-8')+'\n')
        count += 1
    
    f1.close()
    f2.close()
    
def processV(T,V,location1,location2):
    f1 = open(location1,mode='r')
    f2 = open(location2,mode='w')
    
    count = 0
    for line in f1:
        v = V[str(count)]
        us = line.strip().split(',')
        ts = list()
        for i in range(len(us)):
            s = us[i]
            t = T[str(i)]
            ts.append((t,float(s)))
        ts.sort(key = lambda x : -x[1])
        line = json.dumps((v,ts),ensure_ascii=False)
        f2.write(line.encode('utf-8')+'\n')
        count += 1
    
    f1.close()
    f2.close()
    
def invert(location1,location2):
    
    M = dict()
    with open(location1,mode='r') as f:
        for line in f:
            v,ts = json.loads(line)
            for t,s in ts:
                try: M[t]
                except: M[t] = dict()
                M[t][v] = s  
    
    with open(location2,mode='w') as f:
        for t in M.keys():
            vs = [ (v,s) for v,s in M[t].items()]
            vs.sort(key = lambda x : -x[1])
            line = json.dumps((t,vs),ensure_ascii=False)
            f.write(line.encode('utf-8')+'\n')

if __name__ == '__main__':
    
#     T = initM("corpus.2.T.txt")
#     #processT(T,"countT.txt","countT.dat")
#     
#     V = initM("corpus.2.V.txt")
#     processV(T,V,"countV.txt","countV.dat") 

    invert('countV.dat','TV.dat')
    